import Taro, {Component, Config} from '@tarojs/taro'
import {Image, Input, View} from '@tarojs/components'
import {SDBody, SDLoading} from 'sudao-ui'

import './index.less'
import SDUtils from "sudao-utils";

import EmptyIcon from '../../../../images/ic_nothing_search.png'
import CommonEmptyView from '../../../../comps/empty-view'
import orderStatusMapper from "../../orderStatus";


type PageState = {
  keywords: string,
  dataList: any[],
  loading: boolean,
  hasData: boolean,
  hasMore: boolean,
  hideLoading: boolean
}

export default class OrderSearchResultPage extends Component<{}, PageState> {

  constructor () {
    super()
    this.state = {
      keywords: '',
      dataList: [],
      hasData: true,
      hasMore: true,
      hideLoading: false,
      loading: false
    }
  }

  keywords: string = ''

  config: Config = {
    navigationBarTitleText: '搜索结果',
    enablePullDownRefresh: false
  }

  onPullDownRefresh () {
    this.fetchData(0, false, true)
  }

  onReachBottom () {
    const {dataList} = this.state
    this.fetchData(dataList.length)
  }

  componentDidMount () {
    let keywords = (this.$router.params || {}).keywords || ''
    this.keywords = keywords
    this.fetchData(0, true, false)
  }

  fetchData = (offset = 0, resetList = false, hideLoading = false) => {
    const limit = 20
    let { loading, hasData, hasMore, dataList } = this.state
    if (loading || (offset > 0 && !hasMore)) {
      return
    }
    if (offset == 0) {
      dataList = []
    }
    let pageState: any = {
      loading: true,
      hasData: true,
      hasMore: true,
      keywords: this.keywords,
      hideLoading: hideLoading || (dataList.length > 0 && dataList.length < limit)
    }
    if (resetList) {
      pageState.dataList = dataList
    }
    this.setState({
      ...pageState
    },async () => {
      try {
        let resp = await SDUtils.doGet('/wxmini/order', {
          offset: offset,
          limit: limit,
          orderNo: this.keywords,
          orderType: 'SALE_ORDER',    // 固定参数
        })

        dataList = dataList.concat(resp.items || [])
        hasData = resp.total > 0
        hasMore = resp.total > dataList.length
      } catch (e) {
        SDUtils.showMsg(e)
      } finally {
        Taro.stopPullDownRefresh()
        this.setState({
          loading: false,
          hasData: hasData,
          hasMore: hasMore,
          dataList: dataList,
          hideLoading: false
        })
      }
    })
  }

  render () {

    const { loading, keywords, hasData, hasMore, dataList, hideLoading } = this.state

    return (
      <SDBody sd-class='container'>
        <View className="search-content border-bottom_1px">
          <View className="search-outer">
            <Input className="search-input" value={keywords} confirmType='search' placeholder='请输入关键字' onInput={this.onInputValueChange} onConfirm={this.onSearch} />
          </View>
        </View>
        <View style='height: 128rpx;'></View>

        <View className="section-list">
          {
            dataList.map((item, index) => {
              return (
                <View className="section-item" onClick={this.gotoOrderDetail.bind(this, index)} key={index}>
                  <View className="header border-bottom_1px">
                    <View className="title">订单号：{item.orderNo}</View>
                    <View className="sub-title">{orderStatusMapper(item.orderViewStatusEnums)}</View>
                  </View>
                  <View className="sku-list">
                    {
                      (((item.itmes || {}).productViewVo || []).slice(0, 8)).map((innerItem, innerIndex) => {
                        return (
                          <View className="sku-item" key={innerIndex}>
                            <Image className="img" src={innerItem.image}></Image>
                            {/*<View className="tips-content">*/}
                            {/*<View className="title">20个</View>*/}
                            {/*</View>*/}
                          </View>
                        )
                      })
                    }
                  </View>
                  <View className="section-footer">
                    <View className="left">
                      <View className="l_top">
                        <View className="lt_item">商品：{item.productTotalQuantity || 0}</View>
                        <View className="lt_item">规格：{item.skuTotalQuantity}</View>
                        <View className="lt_item">总数: {item.totalQuantity}</View>
                      </View>
                      <View className="l_bottom">{SDUtils.formatDate(item.createTime)}</View>
                    </View>
                    <View className="right">
                      <View className="r_top">
                        <View className="tips">合计：</View>
                        <View className="title">{SDUtils.formatPrice(item.finalTotalAmount)}</View>
                      </View>
                      {
                        item.orderViewStatusEnums == 'PRE_PAY' ? (
                          <View className="r_bottom">
                            <View className="rb_btn">立即支付</View>
                          </View>
                        ) : null
                      }
                    </View>
                  </View>
                </View>
              )
            })
          }

        </View>


        <SDLoading loading={loading} hasMore={hasMore} hasData={hasData} hideLoading={hideLoading}>
          <CommonEmptyView title='暂无数据' icon={EmptyIcon} mainTop={148}/>
        </SDLoading>
      </SDBody>
    )
  }

  onInputValueChange = e => {
    this.keywords = e.detail.value
  }

  onSearch = () => {
    this.execSearch(this.keywords)
  }

  execSearch = keywords => {
    this.setState({
      keywords: keywords,
    }, () => {
      this.fetchData(0, true, false)
    })
  }

  gotoOrderDetail = () => {
    SDUtils.jumpTo('/pages/order/detail/index')
  }

  gotoReturnsDetail = () => {
    SDUtils.jumpTo('/pages/order/returns/detail/index')
  }
}
